<template>
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="table"
        isNeedSelection
        :btnList="btnList"
        :total="totalNum"
        v-model="searchParams"
        :searchShowList="searchShowList"
        :searchHideList="searchHideList"
        :tableColumn="tableColumn"
        requestName="searchHandle"
        :tableData="tableData"
        @add="operateHandle($event, 'add')"
        @edit="operateHandle($event, 'edit')"
        @view="operateHandle($event, 'view')"
        @enable="operateHandle($event, 'enable')"
        @unEnable="operateHandle($event, 'unEnable')"
        @export="operateHandle($event, 'export')"
        @rowEnable="operateHandle($event, 'rowEnable')"
        @rowUnEnable="operateHandle($event, 'rowUnEnable')"
      />
    </div>

    <TrEditPopup
      :width="460"
      v-model="isShowEdit"
      :title="checkTitle"
      :valueObj.sync="formObj"
      :formData="formData"
      :list="popupList"
      @close="isShowEdit = false"
      @confrim="editConfirmHandle"
    />

    <TrDetail
      v-model="isShowDetailPopup"
      :leftList="detailList"
      statusModel="hidden"
      :detailData="detailData"
      :isNeedFooter="false"
      @close="closeDetailPopup"
    />
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  getWorkShop,
  update,
  updateStatus,
} from "@/api/baseCode/lineMaintenance";
import { getColor } from "@/utils/billColor";
import { findByProperty } from "@/utils/util";
import enumData from "@/utils/enumCode.js";

import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrEditPopup from "@/components/Tr-edit/Tr-edit-popup.vue";
import TrDetail from "@/components/Tr-detail/Tr-detail.vue";

export default {
  components: {
    TrTable,
    TrEditPopup,
    TrDetail,
  },
  name: "lineMaintenance",
  data: () => ({
    tableColumn: [
      {
        type: "text",
        label: "线体编码",
        value: "lineCode",
      },
      {
        type: "text",
        label: "线体名称",
        value: "lineName",
      },
      {
        type: "text",
        label: "线体描述",
        value: "remark",
      },
      {
        type: "text",
        label: "所属车间",
        value: "prodOrgName",
      },
      {
        type: "text",
        label: "线体状态",
        value: "isEnabledName",
      },
      {
        type: "text",
        label: "创建人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "text",
        label: "修改人员",
        value: "updateUserName",
      },
      {
        type: "text",
        label: "修改时间",
        value: "updateTime",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "查看",
            option: "view",
          },
        ],
        hideBtnList: [
          {
            label: "启用",
            option: "rowEnable",
          },
          {
            label: "停用",
            option: "rowUnEnable",
          },
          {
            label: "编辑",
            option: "edit",
          },
        ],
      },
    ],
    searchHideList: [
      {
        id: "lineCode",
        type: "input",
        width: 33.33,
        label: "线体编码",
        value: "",
      },
      {
        id: "lineName",
        type: "input",
        width: 33.33,
        label: "线体名称",
        value: "",
      },
      {
        id: "prodOrgId",
        type: "select",
        width: 33.33,
        label: "所属车间",
        value: "",
        list: [],
      },
      {
        id: "isEnabled",
        type: "multiSelect",
        list: [],
        width: 33.3,
        label: "线体状态",
        value: [],
      },
      {
        startStr: "updateTimeStart",
        endStr: "updateTimeEnd",
        id: "modifyTime",
        type: "daterange",
        width: 80,
        label: "修改时间",
        value: [],
        timePeriod: true,
        radio: -1,
      },
    ],
    searchShowList: [
      {
        isNeed: true,
        startStr: "createTimeStart",
        endStr: "createTimeEnd",
        id: "createdTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        timePeriod: true,
        radio: 3,
      },
    ],
    btnList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
      {
        label: "启用",
        option: "enable",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "停用",
        option: "unEnable",
        color: "white",
        isRelaTable: true,
      },
      // {
      //   label: "导出",
      //   option: "export",
      //   color: "white",
      // },
    ],
    tableData: [],
    searchParams: {
      current: 1,
      size: 10,
    },
    totalNum: 0,

    detailData: {},
    isShowDetailPopup: false,
    detailList: [
      {
        type: "text",
        label: "基础信息",
        list: [
          {
            text: "线体名称",
            id: "lineName",
            width: 50,
          },
          {
            text: "线体编号",
            id: "lineCode",
            width: 50,
          },
          {
            text: "所属车间",
            id: "prodOrgName",
            width: 50,
          },
          {
            text: "线体状态",
            id: "isEnabledName",
            width: 50,
          },
          {
            text: "线体描述",
            id: "remark",
            width: 50,
          },
        ],
      },
    ],

    // 新增编辑弹窗
    formObj: {},
    formData: {},
    popupList: [
      {
        label: "线体编码",
        type: "input",
        width: 100,
        value: "",
        id: "lineCode",
        disabled: false,
      },
      {
        label: "线体名称",
        type: "input",
        width: 100,
        value: "",
        id: "lineName",
      },
      {
        label: "所属车间",
        type: "select",
        width: 100,
        value: "",
        id: "prodOrgId",
        list: [],
      },
      {
        label: "是否启用",
        type: "radio",
        width: 100,
        value: 1,
        id: "isEnabled",
        list: [
          { label: "是", value: 1 },
          { label: "否", value: 0 },
        ],
        isNeed: false,
      },
      {
        isNeed: false,
        label: "线体描述",
        type: "textarea",
        width: 100,
        value: "",
        id: "remark",
      },
    ],
    isShowEdit: false,
    currentHandle: "",
    currentRowVal: {},
  }),
  computed: {
    checkTitle() {
      const titles = {
        add: "新增",
        default: "编辑",
      };
      return titles[this.currentHandle] || titles.default;
    },
    ids() {
      let ids = [];
      this.$refs.table.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
  },
  async mounted() {
    await this.getEnmuData();
    await this.getWorkShopHandle();
    // this.getListHandle();
  },
  methods: {
    async getWorkShopHandle() {
      const { data } = await getWorkShop(this.$store.getters.factoryId);

      const workShopItem = findByProperty(this.popupList, "id", "prodOrgId");

      workShopItem.list = data.data.map(({ orgName, id }) => ({
        label: orgName,
        value: id,
      }));
      const workShopScreenItem = findByProperty(
        this.searchHideList,
        "id",
        "prodOrgId"
      );

      workShopScreenItem.list = data.data.map(({ orgName, id }) => ({
        label: orgName,
        value: id,
      }));
    },
    async getEnmuData() {
      const { ["PC-ENABLED-LIST"]: enabled } = await this.$fetchEnumData([
        enumData.isEnabledList,
      ]);

      const enabledItem = findByProperty(
        this.searchHideList,
        "id",
        "isEnabled"
      );

      this.$set(enabledItem, "list", enabled);
    },
    async operateHandle(val, type) {
      this.currentHandle = type;

      this.$validateData(val, 3);

      const lineCodeItem = this.popupList.find((ele) => ele.id === "lineCode");

      if (["add", "edit"].includes(type)) {
        await this.getWorkShopHandle();
      }

      const actions = {
        add: () => {
          lineCodeItem.disabled = false;
          this.formData = {};
          this.isShowEdit = true;
        },
        edit: () => {
          this.currentRowVal = val;
          lineCodeItem.disabled = true;
          this.formData = {
            ...val,
            isEnabled: val.isEnabledName === "启用" ? 1 : 0,
          };
          console.log("formData", this.formData);
          this.isShowEdit = true;
        },
        view: () => this.getDetailHandle(val),
        enable: () => this.updateLineStatus(this.ids, 1, "tip.enableTip"),
        unEnable: () => this.updateLineStatus(this.ids, 0, "tip.unenableTip"),
        export: () =>
          this.$exportHandle({ vm: this, params: this.searchParams }),
        rowEnable: () => this.updateLineStatus([val.id], 1, "tip.enableTip"),
        rowUnEnable: () =>
          this.updateLineStatus([val.id], 0, "tip.unenableTip"),
      };

      const action = actions[type];
      if (action) action();
    },

    // 新增的辅助方法
    async updateLineStatus(ids, status, tipKey) {
      const result = await this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t(tipKey)],
      });
      if (!result) return;

      const { data } = await updateStatus({ ids, isEnabled: status });
      if (data.code !== 200) return;

      this.$message.success(this.$t("msg.success"));
      this.searchParams.current = 1;
      this.getListHandle();
    },

    async getDetailHandle(val) {
      const { data } = await getDetail(val.id);

      if (data.code !== 200) return;

      this.$validateData(data.data);

      this.detailData = data.data;
      const col = this.$findByProperty(
        this.detailList,
        "id",
        "isEnabledName",
        "list"
      );
      col.valueColor =
        {
          0: "#E34D59",
          1: "#00A870",
        }[data.data.isEnabledName === "启用" ? 1 : 0] || "";
      this.isShowDetailPopup = true;
    },
    closeDetailPopup() {
      this.isShowDetailPopup = false;
    },

    searchHandle() {
      this.getListHandle();
    },
    async getListHandle() {
      const { data } = await getList(this.searchParams);
      if (data.code != 200) return;
      this.$validateData(data.data);
      this.tableData = data.data.records;
      this.totalNum = Number(data.data.total);

      this.tableData.forEach((item) => {
        item["isEnabledNameColor"] = getColor("QT", item.isEnabled);
        item["isShowrowEnable"] = item.isEnabled == 1;
        item["isShowrowUnEnable"] = item.isEnabled == 0;
      });
    },
    async addConfirmHandle() {
      const { data } = await add(this.formObj);
      return data.code === 200;
    },
    async editHandle() {
      const { data } = await update({
        ...this.formObj,
        id: this.currentRowVal.id,
      });
      return data.code === 200;
    },
    async editConfirmHandle() {
      let flag = false;

      if (this.currentHandle === "add") {
        flag = await this.addConfirmHandle();
      } else {
        flag = await this.editHandle();
      }
      if (!flag) return;
      this.$message.success(this.$t("msg.success"));
      this.isShowEdit = false;
      this.searchParams.current = 1;
      this.getListHandle();
    },
  },
};
</script>
